{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "view-in-github"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/sugarforever/LangChain-Advanced/blob/main/Integrations/AutoGen/autogen_langchain_uniswap_ai_agent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "39_S0tWcB-oh"
      },
      "source": [
        "# AutoGen + Flowise Use Case\n",
        "\n",
        "**`AutoGen`** is a versatile framework that facilitates the creation of LLM applications by employing multiple agents capable of interacting with one another to tackle tasks. These AutoGen agents can be tailored to specific needs, engage in conversations, and seamlessly integrate human participation.\n",
        "\n",
        "**`Flowise`** is an open source UI visual tool to build customized LLM flows using LangchainJS, written in Node Typescript/Javascript.\n",
        "\n",
        "Flowise has been the leading no-code platform for Langchain based LLM workflow development. You may have already built great features on it.\n",
        "\n",
        "In this tutorial, I will show you how to integrate Flowise flows into AutoGen. You will be able to empower your AutoGen agents with the capability of your Flowise flow, with minimal effort."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NtvjgnBZZjUL"
      },
      "source": [
        "## Use Case - Uniswap Protocol AI Agent with Flowise Flow\n",
        "\n",
        "`Uniswap` is a decentralized exchange that allows users to trade Ethereum-based tokens.\n",
        "\n",
        "In this tutorial, I will walk you through the steps to simplify the AI agent we built in the previous tutorial - [AutoGen + LangChain Use Case - Uniswap Protocol AI Agent](./autogen_langchain_uniswap_ai_agent.ipynb). This agent can execute tasks that involve Uniswap knowledge.\n",
        "\n",
        "We will need much less steps if we have already implemented the QA chain as a Flowise flow.\n",
        "\n",
        "1. Fetch the Python code snippet for Flowise integration.\n",
        "2. Define a function `answer_flowise_uniswap_question`.\n",
        "3. Validate the `answer_flowise_uniswap_question` function.\n",
        "4. Set up AutoGen user agent and assistant agent with function calling enabled.\n",
        "\n",
        "  In the function mapping, the function defined in step 3 is changed to `answer_flowise_uniswap_question`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z73o7bmtb5LH"
      },
      "source": [
        "### Environment Preparation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "execution": {
          "iopub.execute_input": "2023-02-13T23:40:52.317406Z",
          "iopub.status.busy": "2023-02-13T23:40:52.316561Z",
          "iopub.status.idle": "2023-02-13T23:40:52.321193Z",
          "shell.execute_reply": "2023-02-13T23:40:52.320628Z"
        },
        "id": "1VRZnGGGgkhl"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "%pip install pyautogen~=0.1.0 docker -q -U"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "HZ7w_A3nXU8-"
      },
      "outputs": [],
      "source": [
        "import autogen\n",
        "\n",
        "config_list = autogen.config_list_from_json(\n",
        "    \"OAI_CONFIG_LIST\",\n",
        "    filter_dict={\n",
        "        \"model\": [\"gpt-4\"],\n",
        "    },\n",
        ")\n",
        "#\n",
        "# Sample content of OAI_CONFIG_LIST file below:\n",
        "#\n",
        "# [\n",
        "#   {\n",
        "#     \"model\": \"gpt-4\",\n",
        "#     \"api_key\": \"your openai api key\"\n",
        "#   }\n",
        "# ]\n",
        "#"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BA48TH6Hc_3c"
      },
      "source": [
        "### Steps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "#### 1. Fetch the Python code snippet for Flowise integration\n",
        "\n",
        "Click the API Endpoint on the top right corner of your Flowise canvas, and find the Python code snippet similar as below.\n",
        "\n",
        "```python\n",
        "import requests\n",
        "\n",
        "API_URL = \"http://localhost:4000/api/v1/prediction/433ed37e-9546-4e73-a688-7352b78bf852\"\n",
        "\n",
        "def query(payload):\n",
        "    response = requests.post(API_URL, json=payload)\n",
        "    return response.json()\n",
        "    \n",
        "output = query({\n",
        "    \"question\": \"Hey, how are you?\",\n",
        "})\n",
        "```\n",
        "\n",
        "We will reuse it in the AutoGen code base."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O7VPXVI_coX4"
      },
      "source": [
        "#### 2. Define a function `answer_flowise_uniswap_question`\n",
        "\n",
        "It takes a parameter `question`, makes API call to the established Flowise flow, and answer it with the API response."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "yPThjcdFT1Lw"
      },
      "outputs": [],
      "source": [
        "import requests\n",
        "\n",
        "API_URL = \"http://localhost:4000/api/v1/prediction/433ed37e-9546-4e73-a688-7352b78bf852\"\n",
        "\n",
        "def answer_flowise_uniswap_question(question):\n",
        "  response = requests.post(API_URL, json={ \"question\": question })\n",
        "  return response.json()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "#### 3. Validate the `answer_flowise_uniswap_question` function"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'The main changes in Uniswap v3 include the removal of the need for users to track previous values of the accumulator externally, the introduction of multiple pools for each pair of tokens with different swap fees, the implementation of concentrated liquidity within a price range, the use of geometric mean TWAP instead of arithmetic mean TWAP, and the addition of a liquidity accumulator for external contracts to implement liquidity mining.'"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "answer_flowise_uniswap_question(\"What are the main changes in Uniswap v3?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wu7gjAv-c4uP"
      },
      "source": [
        "#### 4. Set up AutoGen user agent and assistant agent with function calling enabled."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "ZsXuHf1fgkhl"
      },
      "outputs": [],
      "source": [
        "llm_config={\n",
        "    \"request_timeout\": 600,\n",
        "    \"seed\": 42,\n",
        "    \"config_list\": config_list,\n",
        "    \"temperature\": 0,\n",
        "    \"functions\": [\n",
        "        {\n",
        "            \"name\": \"answer_flowise_uniswap_question\",\n",
        "            \"description\": \"Answer any Uniswap related questions\",\n",
        "            \"parameters\": {\n",
        "                \"type\": \"object\",\n",
        "                \"properties\": {\n",
        "                    \"question\": {\n",
        "                        \"type\": \"string\",\n",
        "                        \"description\": \"The question to ask in relation to Uniswap protocol\",\n",
        "                    }\n",
        "                },\n",
        "                \"required\": [\"question\"],\n",
        "            },\n",
        "        }\n",
        "    ],\n",
        "}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "eg9g65hOgkhm"
      },
      "outputs": [],
      "source": [
        "# create an AssistantAgent instance named \"assistant\"\n",
        "assistant = autogen.AssistantAgent(\n",
        "    name=\"assistant\",\n",
        "    llm_config=llm_config,\n",
        ")\n",
        "# create a UserProxyAgent instance named \"user_proxy\"\n",
        "user_proxy = autogen.UserProxyAgent(\n",
        "    name=\"user_proxy\",\n",
        "    human_input_mode=\"NEVER\",\n",
        "    max_consecutive_auto_reply=10,\n",
        "    code_execution_config={\"work_dir\": \".\"},\n",
        "    llm_config=llm_config,\n",
        "    system_message=\"\"\"Reply TERMINATE if the task has been solved at full satisfaction.\n",
        "Otherwise, reply CONTINUE, or the reason why the task is not solved yet.\"\"\",\n",
        "    function_map={\"answer_flowise_uniswap_question\": answer_flowise_uniswap_question}\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "37cRtpqLdLSZ"
      },
      "source": [
        "### It's time to start a task for the agents.\n",
        "\n",
        "Now, let's user the user agent to ask the agents to write an introduction blog for `Uniswap` protocol v3."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "aCdAqig3gkhn",
        "outputId": "0deb286b-a1e4-4b56-e8c4-4ab7ea33173f"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[33muser_proxy\u001b[0m (to assistant):\n",
            "\n",
            "\n",
            "I'm writing a blog to introduce the version 3 of Uniswap protocol. Find the answers to the 3 questions below and write an introduction based on them.\n",
            "\n",
            "1. What is Uniswap?\n",
            "2. What are the main changes in Uniswap version 3?\n",
            "3. How to use Uniswap?\n",
            "\n",
            "Start the work now.\n",
            "\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[33massistant\u001b[0m (to user_proxy):\n",
            "\n",
            "\u001b[32m***** Suggested function Call: answer_flowise_uniswap_question *****\u001b[0m\n",
            "Arguments: \n",
            "\n",
            "{\n",
            "  \"question\": \"What is Uniswap?\"\n",
            "}\n",
            "\u001b[32m********************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[35m\n",
            ">>>>>>>> EXECUTING FUNCTION answer_flowise_uniswap_question...\u001b[0m\n",
            "\u001b[33muser_proxy\u001b[0m (to assistant):\n",
            "\n",
            "\u001b[32m***** Response from calling function \"answer_flowise_uniswap_question\" *****\u001b[0m\n",
            "Uniswap is a decentralized exchange protocol that allows users to trade ERC-20 tokens directly from their wallets. In Uniswap version 3, the main change is the introduction of concentrated liquidity, which allows liquidity to be bounded within a specific price range. This is in contrast to earlier versions where liquidity was distributed uniformly along the reserves curve. Uniswap version 3 also introduces multiple pools for each pair of tokens, each with a different swap fee, and includes improvements to the time-weighted average price (TWAP) oracle.\n",
            "\u001b[32m****************************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[33massistant\u001b[0m (to user_proxy):\n",
            "\n",
            "\u001b[32m***** Suggested function Call: answer_flowise_uniswap_question *****\u001b[0m\n",
            "Arguments: \n",
            "\n",
            "{\n",
            "  \"question\": \"What are the main changes in Uniswap version 3?\"\n",
            "}\n",
            "\u001b[32m********************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[35m\n",
            ">>>>>>>> EXECUTING FUNCTION answer_flowise_uniswap_question...\u001b[0m\n",
            "\u001b[33muser_proxy\u001b[0m (to assistant):\n",
            "\n",
            "\u001b[32m***** Response from calling function \"answer_flowise_uniswap_question\" *****\u001b[0m\n",
            "The main changes in Uniswap version 3 include the removal of the need for users to track previous values of the accumulator externally, the introduction of multiple pools for each pair of tokens with different swap fees, the implementation of concentrated liquidity bounded within a price range, tracking the sum of log prices for computing geometric mean TWAP, and the addition of a liquidity accumulator for implementing liquidity mining.\n",
            "\u001b[32m****************************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[33massistant\u001b[0m (to user_proxy):\n",
            "\n",
            "\u001b[32m***** Suggested function Call: answer_flowise_uniswap_question *****\u001b[0m\n",
            "Arguments: \n",
            "\n",
            "{\n",
            "  \"question\": \"How to use Uniswap?\"\n",
            "}\n",
            "\u001b[32m********************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[35m\n",
            ">>>>>>>> EXECUTING FUNCTION answer_flowise_uniswap_question...\u001b[0m\n",
            "\u001b[33muser_proxy\u001b[0m (to assistant):\n",
            "\n",
            "\u001b[32m***** Response from calling function \"answer_flowise_uniswap_question\" *****\u001b[0m\n",
            "Based on the provided context, there are no specific instructions on how to use Uniswap.\n",
            "\u001b[32m****************************************************************************\u001b[0m\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[33massistant\u001b[0m (to user_proxy):\n",
            "\n",
            "Uniswap is a decentralized exchange protocol built on the Ethereum blockchain, allowing users to directly trade ERC-20 tokens from their wallets. It has revolutionized the way users interact with DeFi protocols by providing a platform that is permissionless, transparent, and open to all.\n",
            "\n",
            "The latest version, Uniswap V3, introduces significant changes to enhance the trading experience. The most notable change is the introduction of concentrated liquidity. Unlike previous versions where liquidity was distributed uniformly along the price curve, V3 allows liquidity providers to concentrate their capital within specific price ranges, increasing capital efficiency.\n",
            "\n",
            "Another major change in Uniswap V3 is the introduction of multiple fee tiers for each token pair. This allows liquidity providers to be compensated appropriately for taking on varying degrees of risk. Additionally, improvements have been made to the time-weighted average price (TWAP) oracle, removing the need for users to track previous values of the accumulator externally.\n",
            "\n",
            "To use Uniswap, users need to connect their Ethereum wallet (like MetaMask) to the Uniswap interface. They can then select the tokens they wish to swap, input the amount, and confirm the transaction. Liquidity providers can also add their tokens to the liquidity pool of their choice and earn fees from trades.\n",
            "\n",
            "Please note that while using Uniswap, users should be aware of potential risks such as impermanent loss and smart contract vulnerabilities. Always do your own research and consider your risk tolerance when interacting with DeFi protocols.\n",
            "\n",
            "TERMINATE\n",
            "\n",
            "--------------------------------------------------------------------------------\n",
            "\u001b[33muser_proxy\u001b[0m (to assistant):\n",
            "\n",
            "TERMINATE\n",
            "\n",
            "--------------------------------------------------------------------------------\n"
          ]
        }
      ],
      "source": [
        "# the assistant receives a message from the user, which contains the task description\n",
        "user_proxy.initiate_chat(\n",
        "    assistant,\n",
        "    message=\"\"\"\n",
        "I'm writing a blog to introduce the version 3 of Uniswap protocol. Find the answers to the 3 questions below and write an introduction based on them.\n",
        "\n",
        "1. What is Uniswap?\n",
        "2. What are the main changes in Uniswap version 3?\n",
        "3. How to use Uniswap?\n",
        "\n",
        "Start the work now.\n",
        "\"\"\"\n",
        ")"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "include_colab_link": true,
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.4"
    },
    "vscode": {
      "interpreter": {
        "hash": "949777d72b0d2535278d3dc13498b2535136f6dfe0678499012e853ee9abcab1"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
